using RealtimeCollabGame.Application.Interfaces;
using RealtimeCollabGame.Application.Queries;
using RealtimeCollabGame.Application.DTOs;
using RealtimeCollabGame.Domain.Entities;

namespace RealtimeCollabGame.Application.Handlers;

public class GetGameQueryHandler
{
    private readonly IGameRepository _gameRepository;

    public GetGameQueryHandler(IGameRepository gameRepository)
    {
        _gameRepository = gameRepository;
    }

    public async Task<GameDto?> HandleAsync(GetGameQuery query)
    {
        var game = await _gameRepository.GetByIdAsync(query.GameId);
        if (game == null)
            return null;

        var playerDtos = game.Players.Select((p, index) => new PlayerDto(
            p.Id,
            p.NickName,
            p.Avatar,
            p.Color.Value,
            p.IsOnline,
            p.LastActiveAt,
            index == 0, // 第一个玩家作为房主
            p.IsReady
        )).ToList();

        return new GameDto(
            game.Id,
            game.Name,
            game.Code,
            game.Status,
            game.MaxPlayers,
            game.Players.Count,
            game.GameDuration,
            game.StartedAt,
            game.EndedAt,
            game.GetTimeLeft(),
            game.HasPassword,
            game.HostId,
            playerDtos,
            game.Canvas.Width,
            game.Canvas.Height
        );
    }
}